#!/usr/bin/env python
# This script is defined for compatibility with the Compiler Unit Tests.
# It should not be used for other purposes.
# Specifically it disables dumping stack traces on unhandled exceptions.
# Use build/bin/skip_to_js && tools/run_js directly instead.

# Arguments: sk-files [-- sk-args...]

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import argparse
import imp
import logging
import os
import pipes
import shutil
import subprocess
import sys
import tempfile

import common
import skip_js_compile

VERBOSE = os.environ.get('VERBOSE', '0') == '1'

logger = logging.getLogger(os.path.basename(__file__))
logging.basicConfig(level=logging.DEBUG if VERBOSE else logging.INFO)


def main(stack):
    remainder = common.splitRemainder()
    parser = argparse.ArgumentParser(
        description='Run a skip program in JS',
        parents=[common.commonArguments(needsBackend=False)])
    parser.add_argument('srcs', metavar='SOURCE', nargs='+')
    args = common.parse_args(parser)

    cmd = skip_js_compile.compile(stack, args)
    cmd += tuple(remainder)

    logger.debug('Running: ' + ' '.join(map(pipes.quote, cmd)))

    os.environ['JSLIB'] = common.runtime_dir + '/js'
    with common.PerfTimer('run_js.runtime'):
        common.callHelper(cmd)


if __name__ == '__main__':
    with common.ExitStack() as stack:
        rc = main(stack)
    sys.exit(rc)
